// Created by MyEclipse Struts
// XSL source (default):
// platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_3.8.4/xslt/JavaClass.xsl

package com.novix.struts.action;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import com.novix.portal.framework.model.IPortalUser;
import com.novix.portal.framework.service.IGenericService;
import com.novix.portal.framework.util.IConstants;
import com.novix.portal.framework.util.UserContainer;
import com.novix.struts.form.SearchOrganizationsForm;

/**
 * MyEclipse Struts Creation date: 05-04-2005 XDoclet definition:
 * 
 * @struts:action path="/searchOrganizations" name="searchOrganizationsForm"
 *                input="/form/searchOrganizations.jsp" scope="request"
 *                validate="true"
 * @struts:action-forward name="success" path="/domino/SplashPage"
 *                        redirect="true"
 * @struts:action-forward name="failure" path="/domino/SplashPage"
 *                        redirect="true"
 */
public class SearchOrganizationsAction extends PortalBaseAction {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(SearchOrganizationsAction.class);

    // --------------------------------------------------------- Instance
    // Variables

    // --------------------------------------------------------- Methods

    //	<form-property name="searchkeywords" type="java.lang.String" />
    //	<form-property name="searchtype" type="java.lang.String" />
    //	<form-property name="companyname" type="java.lang.String" />
    //	<form-property name="city" type="java.lang.String" />
    //	<form-property name="state" type="java.lang.String" />    //	
    //	<form-property name="region" type="java.lang.String" />
    /**
     * Method execute
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

        if (isCancelled(request))
            return mapping.findForward(IConstants.HOME);
        SearchOrganizationsForm searchOrganizationsForm = (SearchOrganizationsForm) form;

        String searchkeywords = searchOrganizationsForm.getSearchkeywords();
        String searchtype = searchOrganizationsForm.getSearchtype();
        //    	'search types
        //    	'1 - any keywords
        //    	'2 - all keywords
        //    	'3 - exact phrase match
        //    	
        //    	'build the search from search page values

        int nSearchType = new Integer(searchtype).intValue();
        if (logger.isDebugEnabled())
            logger.debug("" + nSearchType);

        String companyname = searchOrganizationsForm.getCompanyname();
        String NAICS = searchOrganizationsForm.getNAICS();
        String city = searchOrganizationsForm.getCity();
        String state = searchOrganizationsForm.getState();
        String region[] = searchOrganizationsForm.getRegion();
        UserContainer uc = (UserContainer) getUserContainer(request);
        IPortalUser user = uc.getUser();

        String query = generateQuery(user, searchkeywords, nSearchType, companyname, NAICS, city, state, region);

        IGenericService service = getPortalService();
        List list = service.searchWebOrganizationsByQuery(query, user);
        request.setAttribute("list", list);
        return mapping.findForward(IConstants.SUCCESS);
    }

    /**
     * @param searchkeywords
     * @param nSearchType
     * @param companyname
     * @param sic
     * @param city
     * @param state
     * @param region
     */
    private String generateQuery(IPortalUser user, String searchkeywords, int nSearchType, String companyname, String NAICS, String city, String state, String[] region) {
        //[CompanyName] = [IENMemberName] &
        //StringBuffer query = new StringBuffer("[type] = COMPANY &
        // [IENClientStatus] = Member & [IENMemberStatus] = Active " +
        StringBuffer query = new StringBuffer(" [captives]= " + user.getCaptive().trim() + " ");

        getKeywords(searchkeywords, nSearchType, query);

        if (!StringUtils.isBlank(companyname)) {
            addToQuery(query);
            query.append("  [companyname] CONTAINS  " + companyname);
        }
        if (region.length > 0) {
            addToQuery(query);
            query.append("  (");
            for (int i = 0; i < region.length; i++) {
                if (i > 0)
                    query.append(" OR ");
                String filteredVal= StringUtils.replace(region[i].trim(),"N.","");
                filteredVal = StringUtils.replace(filteredVal.trim(),"S.","");
                query.append(" [ienregion] CONTAINS  " + filteredVal.trim() + "");
            }
            query.append(" )");
        }
        if (!StringUtils.isBlank(city)) {
            addToQuery(query);
            query.append("  [officecity] CONTAINS  " + city);
        }
        if (!StringUtils.isBlank(state)) {
            addToQuery(query);
            query.append("   [officestate] CONTAINS  " + state);
        }
        if (!StringUtils.isBlank(NAICS)) {
            addToQuery(query);
            query.append("   [NAICS] CONTAINS " + NAICS);
        }

        if (logger.isDebugEnabled())
            logger.debug(query);

        return query.toString();
    }

    /**
     * @param searchkeywords
     * @param nSearchType
     * @param query
     */
    private void getKeywords(String searchkeywords, int nSearchType, StringBuffer query) {
        String keywords[] = StringUtils.split(searchkeywords);
        switch (nSearchType) {
        case 1:
            if(keywords.length<=0)
                break;
            addToQuery(query);
            for (int i = 0; i < keywords.length; i++) {
                if (i > 0)
                    query.append(" OR ");
                query.append(keywords[i]);
            }
            if (logger.isDebugEnabled())
                logger.debug("any " + nSearchType);
            query.append("  ");
            break;
        case 2:
            if(keywords.length<=0)
                break;
            addToQuery(query);
            for (int i = 0; i < keywords.length; i++) {
                addToQuery(query);
                query.append(keywords[i]);
            }
            if (logger.isDebugEnabled())
                logger.debug("all " + nSearchType);
            break;
        case 3:
            if(keywords.length<=0)
                break;
            addToQuery(query);
            query.append(searchkeywords);
            query.append("\")");
            if (logger.isDebugEnabled())
                logger.debug("exact " + nSearchType);
            break;
        default:
            break;
        }
    }

    /**
     * @param query
     */
    private void addToQuery(StringBuffer query) {
        String sQuery = query.toString().trim();
        int length = sQuery.length();
        if (length > 0) {
            if (sQuery.substring(length - 3, length).compareToIgnoreCase("AND") != 0) {
                query.append(" AND ");
            }
        }
    }

}